<?php
//留言
define('IN_T', true);
require 'include/init.php';

$act = Common::sfilter($_REQUEST["act"]);

//商家id
$c_id = intval($_REQUEST['cid']);
//新闻id
$nid = intval($_REQUEST['nid']);

//写入评论
if ($act == 'comment') {
    //写入评论
    $res['status'] = 0;
    $data = array(
        'name' => Common::sfilter($_POST['name']),
        'phone' => Common::sfilter($_POST['phone']),
        'comment' => Common::sfilter($_POST['comment'], 'html'),
        'new_id' => $nid,
    );

    if($c_id > 0){
        //商户留言
        $data['c_id'] = $c_id;
    }
    if (empty($data['name'])) {
        $res['msg'] = '请填写您的姓名';
    }
	else if (empty($data["phone"]) || !Common::is_mobile($data["phone"])) {
        $res['msg'] = '请填写正确的手机号';
    }
	else if (empty($data["comment"])) {
        $res['msg'] = '请填写留言内容';
    }
	else {
        $Db->insert($Base->table('company_new_comment'), $data);
        $res = array('status' => 1, 'msg' => '留言成功');
    }
    echo $Json->encode($res);
    exit;
}
//获取评论列表
elseif ($act == "ajaxComment") {
    $page = intval($_REQUEST['page']);
    $page = $page < 1 ? 1 : $page;
    $size = 10;
    $list = get_ajax_comments($c_id,$nid, $page, $size);
    echo $Json->encode($list);
    exit;
}
//显示评论列表
else{
	//读取商户基本信息
	$sql = "SELECT cp.comment_name, cp.c_id, cp.name FROM " . $Base->table('company_profile') . " as cp " .
		   "WHERE cp.c_id = $c_id";

	$cp = $Db->query($sql, "Row");

	//商家不存
	if (empty($cp)) {
		echo '商家不存在或未完善基本信息！';
		exit;
	}

	$tp->assign('cp',$cp);
	$tp->display('comment.tpl');
}

function get_ajax_comments($c_id,$nid, $page, $size){
	$sql = "select * from ".$GLOBALS['Base']->table('company_new_comment')." where new_id=$nid and pid=0 ";
	if($c_id > 0){
	    $sql .= "and c_id=".$c_id .' ';
    }
	$sql .= "order by id desc limit ".($page-1)*$size.", $size";
	$res = $GLOBALS['Db']->query($sql);
    //读取管理员回复
    foreach ($res as $k => $v) {
        $res[$k]["child"] = $GLOBALS['Db']->query("select * from ".$GLOBALS['Base']->table('company_new_comment')." where pid=".$v['id']." ");
    }
	//print_r($res);
    return $res;
}

?>